package admin

import (
	"context"
	"errors"
	"sort"
	"strings"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/datatypes"
)

type ProductSkuSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewProductSkuSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductSkuSaveLogic {
	return &ProductSkuSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ProductSkuSaveLogic) ProductSkuSave(req *types.ProductSkuSaveReq) (resp string, err error) {
	if !utils.GetDataById(req.ProductID, &models.Product{}) {
		return "", errors.New("商品不存在")
	}

	specIds := strings.Split(req.SpecIds, ",")
	if len(specIds) == 0 {
		return "", errors.New("请选择规格")
	}
	sort.Strings(specIds)
	specName := []string{}
	for _, v := range specIds {
		vt := strings.Split(v, ":")
		tmpKey := &models.SpecKey{}
		if !utils.GetDataById(utils.StringToUint(vt[0]), tmpKey) {
			return "", errors.New("规格不存在")
		}
		tmpValue := &models.SpecValue{}
		if !utils.GetDataById(utils.StringToUint(vt[0]), tmpValue) {
			return "", errors.New("规格值不存在")
		}
		specName = append(specName, tmpKey.Name+":"+tmpValue.Value)
	}
	check := &models.ProductSku{
		ProductID: req.ProductID,
		SpecIds:   datatypes.JSON(utils.StructToJson(specIds)),
	}

	checkResult := utils.GetData(check)
	if (checkResult && req.Id == 0) || (checkResult && req.Id != check.ID) {
		return "", errors.New("商品SKU已存在")
	}

	data := &models.ProductSku{
		ProductID:    req.ProductID,
		Price:        req.Price,
		MarketPrice:  req.MarketPrice,
		Stock:        req.Stock,
		StockWarning: req.StockWarning,
		Image:        req.Image,
		IsDefault:    req.IsDefault,
		SpecIds:      datatypes.JSON(utils.StructToJson(specIds)),
		Specs:        datatypes.JSON(utils.StructToJson(specName)),
	}

	if req.Id == 0 {
		err = utils.InsertData(data)
	} else {
		err = utils.UpdateById(req.Id, data)
	}

	if err != nil {
		logx.Errorf("操作商品失败: %v", err)
		return "", err
	}

	if req.Id == 0 || utils.StructToJson(data.SpecIds) != utils.StructToJson(specIds) {
		//删除之前的数据
		utils.DeleteData(&models.SkuSpecRelation{SkuID: data.ID})
		//插入新的数据
		skuSpec := make([]*models.SkuSpecRelation, 0)
		for k, v := range specIds {
			vt := strings.Split(v, ":")
			vn := strings.Split(specName[k], ":")
			tmp := &models.SkuSpecRelation{
				SkuID:       data.ID,
				SpecKeyID:   utils.StringToUint(vt[0]),
				SpecKeyName: vn[0],
				SpecValueID: utils.StringToUint(vt[1]),
				SpecValue:   vn[1],
				ProductID:   req.ProductID,
			}
			skuSpec = append(skuSpec, tmp)
		}
		if err = utils.InsertData(skuSpec); err != nil {
			return "", err
		}
	}

	return "操作成功", nil
}
